/*
 * @Description: 姓名或身份证解密
 * @Author: huacong
 * @Date: 2020-06-01 14:52:54
 * @LastEditTime: 2020-11-04 13:29:46
 * @LastEditors: huacong
 */
const decodeKeys = ['name', 'idcard', 'idCard', 'relativeName', 'relativeIdcard']

// 解密
function decryptByDES (message, key) {
  const CryptoJS = window.CryptoJS || null
  if (CryptoJS) {
    const keyHex = CryptoJS.enc.Utf8.parse(key)
    const decrypted = CryptoJS.DES
      .decrypt({
        ciphertext: CryptoJS.enc.Base64.parse(message)
      }, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
    const resultValue = decrypted.toString(CryptoJS.enc.Utf8)
    return resultValue
  }
}

// 判断字符串是否为空
function isEmpty (obj) {
  if (typeof obj === 'undefined' || obj === null || obj === '' || obj === 'null') {
    return true
  } else {
    return false
  }
}
// 递归遍历请求参数，对其进行解密
export function replaceParam (str) {
  if (str instanceof Object) {
    if (str instanceof Array) {
      for (let i = 0, l = str.length; i < l; i++) {
        for (const key in str[i]) {
          if (str[i][key] instanceof Object) {
            str[i][key] = replaceParam(str[i][key])
          } else {
            if ((decodeKeys.includes(key)) && !isEmpty(str[i][key])) {
              let value = decryptByDES(str[i][key], '2136464589fgbcde')
              if (key === 'idcard' || key === 'idCard') {
                // 身份证号码隐藏中间11位
                value = changeStr(value, 3, -4)
              }
              str[i][key] = value
            }
          }
        }
      }
    } else {
      for (const key in str) {
        if (str[key] instanceof Object) {
          str[key] = replaceParam(str[key])
        } else {
          if ((decodeKeys.includes(key)) && !isEmpty(str[key])) {
            str[key] = decryptByDES(str[key], '2136464589fgbcde')
          }
        }
      }
    }
  }
  return str
}

// str:原始字符串，index,开始位置,lastIndex倒数职位
function changeStr (str, index, lastIndex) {
  const num = str.length + lastIndex - index
  const changeStr = new Array(num).fill('*').join('')
  return str.substr(0, index) + changeStr + str.substr(lastIndex)
}
